package org.jeecg.modules.demo.weixin.payorder.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.demo.weixin.dto.SpiltOrderDto;
import org.jeecg.modules.demo.weixin.entity.PayOrder;
import org.jeecg.modules.demo.weixin.entity.SmtDev;
import org.jeecg.modules.demo.weixin.payorder.service.IPayOrderService;
import org.jeecg.modules.demo.weixin.smtdev.service.ISmtDevService;
import org.jeecg.modules.demo.weixin.smtyuyuelist.service.ISmtYuyueListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: pay_order
 * @Author: jeecg-boot
 * @Date: 2023-10-23
 * @Version: V1.0
 */
@Api(tags = "pay_order")
@RestController
@RequestMapping("/weixin/payorder/payOrder")
@Slf4j
public class PayOrderController extends JeecgController<PayOrder, IPayOrderService> {
    @Autowired
    private IPayOrderService payOrderService;

    @Autowired
    private ISmtYuyueListService yuyueListService;
    @Autowired
    private ISmtDevService smtDevService;

    /**
     * 分页列表查询
     *
     * @param payOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "pay_order-分页列表查询", notes = "pay_order-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<PayOrder>> list(PayOrder payOrder,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                        HttpServletRequest req) throws ParseException {
        Page<PayOrder> page = new Page<PayOrder>(pageNo, pageSize);
        QueryWrapper<PayOrder> queryWrapper = new QueryWrapper<>();
        if (payOrder.getSplitType() != null) {
            queryWrapper.in("split_type", payOrder.getSplitType());
        }
        if (StringUtils.isNoneBlank(payOrder.getOrderIds())) {
            String[] split = payOrder.getOrderIds().split(",");
            List<Integer> integerList = Arrays.asList(split).stream().map(s -> Integer.valueOf(s)).collect(Collectors.toList());
            queryWrapper.in("id", integerList);
        }
        LambdaQueryWrapper<SmtDev> smtDevLambdaQueryWrapper = new LambdaQueryWrapper<>();
        smtDevLambdaQueryWrapper.eq(SmtDev::getMerchantId, payOrder.getMerId());
        List<SmtDev> smtDevList = smtDevService.list(smtDevLambdaQueryWrapper);        //如果有门店的话  排期不排期的不显示
        if (StringUtils.isNotBlank(payOrder.getMerId())) {
            //根据场次id获取门店对应订单
            List<String> yuyueIds = yuyueListService.queryMerList(payOrder.getMerId());
            //如果yuyueIds未null 则没有数据 且 ordertype不等于null
            if (payOrder.getOrderType() != null) {

                if (!CollectionUtils.isEmpty(smtDevList)) {
                    List<String> devList = smtDevList.stream().map(SmtDev::getDevCode).collect(Collectors.toList());
                    queryWrapper.and(payOrderQueryWrapper -> payOrderQueryWrapper.in("dev_code", devList).or().eq("merchant_id", payOrder.getMerId()));
                } else queryWrapper.eq("merchant_id", payOrder.getMerId());

                queryWrapper.eq("order_type", payOrder.getOrderType());
            }
            //如果订单类型为空则   排期和不排期都显示
            if (payOrder.getOrderType() == null) {
                if (!CollectionUtils.isEmpty(smtDevList)) {
                    List<String> devList = smtDevList.stream().map(SmtDev::getDevCode).collect(Collectors.toList());
                    queryWrapper.and(payOrderQueryWrapper -> payOrderQueryWrapper.in("yuyue_id", yuyueIds).or().in("dev_code", devList).or().eq("merchant_id", payOrder.getMerId()));
                }
                queryWrapper.and(payOrderQueryWrapper -> payOrderQueryWrapper.in("yuyue_id", yuyueIds).or().eq("merchant_id", payOrder.getMerId()));
            }

        }
        if (StringUtils.isBlank(payOrder.getMerId()) && payOrder.getOrderType() != null) {
            queryWrapper.eq("order_type", payOrder.getOrderType());
        }
        if (payOrder.getUserId() != null) {
            queryWrapper.eq("user_id", payOrder.getUserId());
        }
        //判断当前收银员的权限
        if (payOrder.getRechargeUser() != null) {
            queryWrapper.eq("recharge_user", payOrder.getRechargeUser());
        }
        if (StringUtils.isNotBlank(payOrder.getPayStatus())) {
            queryWrapper.eq("pay_status", payOrder.getPayStatus());
        }
        if (StringUtils.isNotBlank(payOrder.getStartTime())) {
            queryWrapper.apply("DATE(create_time) like '" + payOrder.getStartTime() + "'");
        }
        queryWrapper.orderByDesc("create_time");
        IPage<PayOrder> pageList = payOrderService.page(page, queryWrapper);
        if (CollectionUtils.isEmpty(pageList.getRecords())) {
            return Result.OK(pageList);
        }
        //
        if (StringUtils.isNotBlank(payOrder.getMerId())) {
            List<PayOrder> payOrders = payOrderService.queryUserdetails(pageList.getRecords(), payOrder.getMerId());
            return Result.OK(pageList.setRecords(payOrders));
        }
        return Result.OK(pageList);
    }

    /**
     * 平台、商家端分页列表查询订单
     *
     * @param payOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "平台、商家端分页列表查询订单", notes = "平台、商家端分页列表查询订单")
    @GetMapping(value = "/queryList")
    public Result<IPage<PayOrder>> queryList(PayOrder payOrder,
                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                             HttpServletRequest req) throws ParseException {
        //如果商家id不为null则是商家端查询
        if (StringUtils.isNotBlank(payOrder.getMerId())) {
            payOrder.setMerchantId(payOrder.getMerId());
        }
        QueryWrapper<PayOrder> queryWrapper = QueryGenerator.initQueryWrapper(payOrder, req.getParameterMap());
        queryWrapper.orderByDesc("create_time");
        Page<PayOrder> page = new Page<PayOrder>(pageNo, pageSize);
        IPage<PayOrder> pageList = payOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 平台分账订单查询接口   只有扫码支付的
     *
     * @param payOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "平台分账订单查询接口", notes = "平台分账订单查询接口")
    @GetMapping(value = "/queryProfitSharing")
    public Result<IPage<PayOrder>> queryProfitSharing(PayOrder payOrder,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest req) throws ParseException {
        QueryWrapper<PayOrder> queryWrapper = QueryGenerator.initQueryWrapper(payOrder, req.getParameterMap());
        queryWrapper.orderByDesc("create_time");
        queryWrapper.ne("pay_price", BigDecimal.ZERO);
        Page<PayOrder> page = new Page<PayOrder>(pageNo, pageSize);
        IPage<PayOrder> pageList = payOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param payOrder
     * @return
     */
    @AutoLog(value = "pay_order-添加")
    @ApiOperation(value = "pay_order-添加", notes = "pay_order-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody PayOrder payOrder) {
        payOrderService.save(payOrder);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param payOrder
     * @return
     */
//    @AutoLog(value = "pay_order-编辑")
    @ApiOperation(value = "pay_order-编辑", notes = "pay_order-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody PayOrder payOrder) {
        payOrderService.updateById(payOrder);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
//    @AutoLog(value = "pay_order-通过id删除")
    @ApiOperation(value = "pay_order-通过id删除", notes = "pay_order-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        payOrderService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "pay_order-批量删除")
    @ApiOperation(value = "pay_order-批量删除", notes = "pay_order-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.payOrderService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "pay_order-通过id查询")
    @ApiOperation(value = "pay_order-通过id查询", notes = "pay_order-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<PayOrder> queryById(@RequestParam(name = "id", required = true) Integer id) {
        PayOrder payOrder = payOrderService.getById(id);
        if (payOrder == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(payOrder);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param payOrder
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PayOrder payOrder) {
        return super.exportXls(request, payOrder, PayOrder.class, "pay_order");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, PayOrder.class);
    }

    /**
     * 通过id查询
     *
     * @param spiltOrderDto
     * @return
     */
    //@AutoLog(value = "pay_order-通过id查询")
    @PostMapping(value = "/splitOrder")
    public Result<PayOrder> splitOrder(@RequestBody SpiltOrderDto spiltOrderDto) {
        if (spiltOrderDto.getRecordId() != null) {
//            payOrderService.calcOrderRecordId(spiltOrderDto.getRecordId());
        } else if (StringUtils.isNoneBlank(spiltOrderDto.getMerichantId())) {
//            payOrderService.calcOrderMerchantId(spiltOrderDto.getMerichantId());
        } else payOrderService.calcOrder();
        return Result.OK();
    }


    /**
     * 通过id查询
     *
     * @param spiltOrderDto
     * @return
     */
    //@AutoLog(value = "pay_order-通过id查询")
    @PostMapping(value = "/dailyMerchant")
    public Result<Object> dailyMerchant(@RequestBody SpiltOrderDto spiltOrderDto) {
        LocalDateTime startTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String start = df.format(startTime);
        String end = df.format(endTime);
        return Result.OK(payOrderService.dailyMerchant(null, start, end));
    }


}
